#include "ModelLoader.h"

ModelLoader::ModelLoader(ResourceManager* rm)
	:Component(COMP_MODEL_LOADER),
	m_resourceManager(rm)
{
}

ModelLoader::~ModelLoader()
{

}


void ModelLoader::AddedToObject()
{
	RequestMessage(MSG_LOAD_MODEL,&ModelLoader::Load);
}

void ModelLoader::Load(const Message& msg)
{
	string name;
	string path;
	AuxUnGroupArgus(msg.p,name);
	SendMessage(MSG_GET_PATH,AuxGroupArgus(name,&path));
	Load(path);
}

/*
Load the model in DataStream.
send a global message to other component which need the model.
Add this model to ResourceManager
*/
void ModelLoader::Load(string path)
{
	try
	{
	Model::ModelInfoPtr tmpInfo=boost::make_shared<ModelInfo>();
	if(path!="")
	{
		DataStream ds(path);
		Mesh::sPtr tmpMesh;
		Chunk* mainChunk=ds.GetMainChunk();
		if(!mainChunk->HasSubChunk())
			EXCEPTION("");
		string meshName;
		for(Chunk::ChunkIterator iter=mainChunk->GetSubChunkBegin();iter!=mainChunk->GetSubChunkEnd();iter++)
		{
			const char* data=(*iter)->GetData();
			if((*iter)->GetID()=="mesh")
			{
				meshName=data;

				if(!m_resourceManager->IsLoaded(Resource::MESH,meshName))
				{
					string meshPath;
					SendMessage(MSG_GET_PATH,AuxGroupArgus(meshName,&meshPath));
					SendMessage(MSG_LOAD_MESH,AuxGroupArgus(meshPath));
				}
				tmpMesh=boost::shared_dynamic_cast<Mesh>(m_resourceManager->GetResource(Resource::MESH,meshName));
				if(tmpMesh==NULL)
					EXCEPTION("")
			}
			else if((*iter)->GetID()=="anim_speed")
			{
				memcpy(&tmpInfo->speed,data,sizeof(float));
			}
			else if((*iter)->GetID()=="anim")
			{
				memcpy(&tmpInfo->anim,data,sizeof(int));
			}
			else if((*iter)->GetID()=="pos")
			{
				float x=0,y=0,z=0;
				char* p=data;
				memcpy(&x,p,sizeof(float));
				p+=sizeof(float);
				memcpy(&y,p,sizeof(float));
				p+=sizeof(float);
				memcpy(&z,p,sizeof(float));
				p+=sizeof(float);
				tmpInfo->pos=XMFLOAT3(x,y,z);
			}
			else
			{
				EXCEPTION("")
			}
		}
		if(tmpMesh->GetMeshUsage()!=MESH_UNKNOWN)
		{
			Model::sPtr tmpModel=boost::make_shared<Model>(ds.GetChunkName(),tmpMesh,tmpInfo,RenderObject::RenderWithCameraWithTexture);
			AddLocalComponent(tmpModel);
			m_resourceManager->AddResource(Resource::MODEL,ds.GetChunkName(),tmpModel);
			SendMessage(MSG_ADD_RENDER_OBJECT,AuxGroupArgus(boost::shared_dynamic_cast<RenderObject>(tmpModel)));
		}
		else
		{
			EXCEPTION("")
		}


	}
	else
	{
		EXCEPTION("")
	}
	}
	catch(std::exception& e)
	{
		PRINT_ERROR(e);
	}
}


